//
//  ViewController.m
//  FMDB0629
//
//  Created by boldseas on 2017/6/29.
//  Copyright © 2017年 renbohan. All rights reserved.
//

#import "ViewController.h"
#import <FMDB.h>

@interface ViewController ()

@property (nonatomic, strong) FMDatabaseQueue *queue;

@end

@implementation ViewController
- (IBAction)add {
    [_queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"insert into t_user (name,money) values (?,?)", @"a",@1000];
        BOOL flag = [db executeUpdate:@"insert into t_user (name,money) values (?,?)", @"b",@500];
        if (flag) {
            NSLog(@"增加成功");
        }else{
            NSLog(@"增加失败");
        }
    }];
    
}


- (IBAction)delete {
    [_queue inDatabase:^(FMDatabase *db) {
        BOOL flag = [db executeUpdate:@"delete from t_user"];
        if (flag) {
            NSLog(@"删除成功");
        }else{
            NSLog(@"删除失败");
        }
    }];
}


- (IBAction)update {
    [_queue inDatabase:^(FMDatabase *db) {
        
        [db beginTransaction];
        bool flag = [db executeUpdate:@"update t_user set money = ? where name = ?",@500,@"a"];
        if (flag) {
            NSLog(@"修改成功");
        }else{
            NSLog(@"修改失败");
            [db rollback];
        }
        
        BOOL flag1 = [db executeUpdate:@"update t_user set mony = ? where name = ?",@1000,@"b"];
        if (flag1) {
            NSLog(@"flag1修改成功");
        }else{
            NSLog(@"flag1修改失败");
            [db rollback];
        }
        [db commit];
    }];
}


- (IBAction)select {
    [_queue inDatabase:^(FMDatabase *db) {
        FMResultSet *set = [db executeQuery:@"select * from t_user"];
        while ([set next]) {
            NSString *name = [set stringForColumn:@"name"];
            int money = [set intForColumn:@"money"];
            NSLog(@"%@---%d", name, money);
        }
    }];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [doc stringByAppendingPathComponent:@"user.sqlite"];
    
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:path];
    _queue = queue;
    
    [queue inDatabase:^(FMDatabase *db) {
        bool flag = [db executeUpdate:@"create table if not exists t_user (id integer primary key autoincrement, name text, money integer)"];
        
        if (flag) {
            NSLog(@"创建成功");
        }else{
            NSLog(@"创建失败");
        }
    }];
}


@end
